import { View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import { saveFoodMixIngredients, useFoodMixIngredients } from 'src/hooks/useFoods';
import { useMixIngredients } from 'src/hooks/useMixIngredients';
import { AtButton, AtIcon, AtList } from 'taro-ui';
import { Picker } from 'src/components/picker'
import { Empty } from 'src/components/empty';
import { showToast } from 'src/utils/toast';

import './index.less';

function AddMix() {
  const params = Taro.getCurrentInstance()?.router?.params
  const foodId = params?.foodId

  const { foodWithMixIngredients, setFoodMixIngredients, fetchFoodMixIngredients } = useFoodMixIngredients(foodId)
  const mixIngredients = foodWithMixIngredients?.mixIngredients || []
  const [allMixIngredients] = useMixIngredients()

  const validate = () => {
    // 有任何一项没有 id 则不通过
    return mixIngredients.every(item => item.id)
  }

  const handleAdd = () => {
    const newMixIngredients = [...mixIngredients]
    // 添加新的空项
    newMixIngredients.push({name: ''})
    setFoodMixIngredients(newMixIngredients)
  }

  const handleChange = (index: number) => {
    return (value) => {
      // 替换为新值
      const newMixIngredients = [...mixIngredients]
      const newMixIngredient = allMixIngredients.find(item => item.id === value)
      if (newMixIngredient) {
        newMixIngredients.splice(index, 1, newMixIngredient)
        // 更新
        setFoodMixIngredients(newMixIngredients)
      }
    }
  }

  const handleDelete = (index: number) => {
    return () => {
      // 删除
      const newMixIngredients = [...mixIngredients]
      newMixIngredients.splice(index, 1)
      setFoodMixIngredients(newMixIngredients)
    }
  }

  const handleSubmit = async () => {
    // 校验
    if (!validate()) {
      Taro.showToast({
        title: '请填写完整',
        icon: 'none',
      })
      return
    }

    // 保存
    await saveFoodMixIngredients(foodId!, mixIngredients.map(item => item.id!))
    showToast('保存成功')
    // 重新获取
    await fetchFoodMixIngredients()
  }

  const filterMethod = (item) => {
    return !mixIngredients.some(mixIngredient => mixIngredient.id === item.id)
  }

  return (
    <View>
      <View className='body'>
        {
          mixIngredients.length > 0 ?
          <AtList hasBorder={false}>
            {
              mixIngredients.map((mixIngredient, index) => (
                <View key={mixIngredient.id} className='add-mix-item'>
                  <Picker
                    className='add-mix-item__picker'
                    options={allMixIngredients}
                    value={mixIngredient.id}
                    onChange={handleChange(index)}
                    filterMethod={filterMethod}
                    noteKey='remark'
                  />
                  <AtIcon
                    className='add-mix-item__delete'
                    value='subtract-circle'
                    size='20'
                    color='#F00'
                    onClick={handleDelete(index)}
                  />
                </View>
              ))
            }
          </AtList> :
          <Empty />
        }
        <AtButton
          type='secondary'
          className='add-mix__add-btn'
          onClick={handleAdd}
        >
          添加关联
        </AtButton>
        <AtButton
          type='primary'
          className='add-mix__submit-btn'
          onClick={handleSubmit}
        >
          保存关联
        </AtButton>
      </View>
    </View>
  );
}

export default AddMix;
